Skip to content

feat(codegen-ts): add service and service-routes generators (ADR-0067 layers 4 and 5) - #641

Merged
dmealing merged 7 commits into
mainfrom
fm/mo-130-lane-ts-2-b6
Nov 22, 2026
Merged

dmealing merged 7 commits into
mainfrom
fm/mo-130-lane-ts-2-b6

Conversation

@dmealing

@dmealing dmealing commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

What Changed

  • Adds two opt-in TypeScript generators, service and service-routes, backed by new codegen-ts walk and template modules plus ejectable reference copies. service writes one module per metadata package. Each concrete, table-backed, single-key entity gets derived list, get, create, update and delete functions, plus create<Pkg>Service(deps). Every write runs in one transaction (a savepoint inside a caller's opts.tx), loads the row under a row lock, and validates and stamps the input with the declared write rules (ADR-0045). service-routes writes a thin Fastify plugin per package over that service. @metaobjectsdev/runtime-ts gains the ./service and ./service/fastify entries these import, and meta eject copies them. Write-through, TPH, many-to-many, projections, reports, transitions and declared operations stay on the flat generators.
  • Adds a service layer label to the shared generator registry manifest, with service and service-routes rows (TypeScript only). The C#, Java, Kotlin and Python registries and their conformance tests accept the new label. Registry, eject and byte-identical reference tests are updated, and the CLI catalog listing and install set know the new generators.
  • Adds an api-contract lane that runs the shared corpus against the service behind its transport, in both layouts, with the existing generated-server helpers refactored into a shared lane module. A compile gate builds the service tier in every dialect, alongside new unit tests for the generator and the runtime service module. Docs are updated in business-rules.md, own-your-codegen.md, docs/ports/typescript.md, the codegen skill and its agent-context goldens, ADR-0067, and the CHANGELOG.
Validation

Risk Assessment

✅ Low: The change adds two opt-in generators and a runtime module, and the flat generators' output is unchanged. It meets the stated L-TS-4 intent. The earlier fix rounds (async-only sqlite Db, regenerated goldens and shipped bundle) hold up on re-read, and I found no new defect.

Testing

I ran the focused checks for the service generator against real runtimes. The baseline scripts/ci-local.sh --affected --strict-toolchains had already passed. The generated service plus transport passed the shared API-contract corpus over HTTP against Testcontainers Postgres. Its emitted code compiled. The runtime service module passed its own tests, and meta gen --list shows the new service layer. The C# generator-registry and drift tests also passed, including the GUID-narrowed temp-dir test. No source changes were made and no containers I started remain.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
Generated service module plus thin Fastify transport passes the shared api-contract corpus (HTTP lane against Testcontainers Postgres) ✅ pass live bun test test/api-contract-service.test.ts test/service-compile.test.ts in integration-tests: 80 pass, 0 fail. The lane generates the service and transport, boots them over HTTP, and the emitted cod…
The service runtime module runs derived writes in one transaction with write rules, and the generator registry lists the new layer (meta gen --list shows service, layer service, requires entit… ✅ pass live runtime-ts service.test.ts 14 pass. codegen-ts service-file.test.ts and generator-registry.test.ts 24 pass, including the async-only sqlite Db alias. The meta gen --list transcript is in gen…
Cross-port generator registry conformance accepts the new service layer, and the C# drift test ignores temp dirs from other tools ✅ pass live dotnet test in server/csharp: 11 pass in MetaObjects.Codegen.Tests, covering CodegenDriftTests and GeneratorRegistryConformance.
Evidence: meta gen --list output (includes the service layer entry)
[37]:
  - name: barrel
    kind: generator
    layer: model
    tier: native
    package: @metaobjectsdev/codegen-ts
    description: Single index.ts re-exporting every generated entity module.
    useWhen: you want a single `index.ts` re-exporting every generated entity module.
    emits: "<target>/index.ts with one `export * from \"./<Entity>\"` per entity, alphabetical."
    requires[1]: entity
    configKeys[1]: extStyle
    install:
      dev[1]: @metaobjectsdev/codegen-ts@^1.3.0
      runtime: []
    wire:
      import: "import { barrel } from \"@metaobjectsdev/codegen-ts/generators\";"
    source:
      kind: reference-template
      ejectable: true
      owned: null
  - name: contract-types
    kind: generator
    layer: model
    tier: native
    package: @metaobjectsdev/codegen-ts
    description: "Contract types with no persistence mapping: read, create and update shapes, operation inputs and outputs, and the wire error bodies."
    useWhen: "a transport, a client, a job or another service needs the shapes a service takes and returns, and the wire errors it answers with, without importing the ORM."
    emits: "<Entity>.contract.ts (read, create and update shapes), <Projection>.contract.ts (read shape), the value modules they reach, enums.ts, errors.contract.ts at the target root, and <pkg path>/operations.contract.ts per package that declares operations. A model with no store-backed entity, projection or operation gets no file."
    requires: []
    install:
      dev[1]: @metaobjectsdev/codegen-ts@^1.3.0
      runtime[1]: zod
    wire:
      import: "import { contractTypes } from \"@metaobjectsdev/codegen-ts/generators\";"
    source:
      kind: reference-template
      ejectable: true
      owned: null
  - name: entity
    kind: generator
    layer: model
    tier: native
    package: @metaobjectsdev/codegen-ts
    description: Per-entity Drizzle table + typed model module (the entity module).
    useWhen: "ALWAYS — this is the entity-module generator. It owns the shape of each generated <Entity>.ts (the Drizzle table, Zod schemas, inferred types, constants, filter allowlists). Start here and adapt the assembly."
    emits: "<target>/<Entity>.ts per concrete object — and the shared-enums module once. Dispatches: abstract/value → interface + Zod; sourceless entity (identity, no source — a MongoDB/Cassandra/Neo4j record) → interface + create/PATCH Zod + allowlists; projection → read-only view decl; write-through entity → full Drizzle table path."
    requires: []
    configKeys[7]: dialect,extStyle,outputLayout,pluralizeCollections,collectionNameOverrides,providedEnumModule,apiPrefix
    install:
      dev[1]: @metaobjectsdev/codegen-ts@^1.3.0
      runtime[3]: @metaobjectsdev/runtime-ts@^1.3.0,drizzle-orm@>=0.36.0 <1.0.0,zod@>=3.23.0 <5.0.0
    wire:
      import: "import { entityFile } from \"@metaobjectsdev/codegen-ts/generators\";"
    source:
      kind: reference-template
      ejectable: true
      owned: null
  - name: names
    kind: generator
    layer: model
    tier: native
    package: @metaobjectsdev/codegen-ts
    description: "Per-entity physical database name constants (table/view, schema, columns)."
    useWhen: "you want the physical database names (table/view + column names) for each object available as importable constants, so a hand-written consumer never has to embed a name as a string literal a second time."
    emits: "<target>/<Entity>.names.ts per concrete object with a primary source (under outputLayout: \"package\", <target>/<pkg>/<Entity>.names.ts — beside the entity module it describes). An object with no primary source (#248) gets no names artifact — EXCEPT an abstract base that a sourced object extends, which gets a fragment (columns, no physical name) so its children extend it instead of restating every inherited column."
    install:
      dev[1]: @metaobjectsdev/codegen-ts@^1.3.0
      runtime: []
    wire:
      import: "import { namesFile } from \"@metaobjectsdev/codegen-ts/generators\";"
    source:
      kind: reference-template
      ejectable: true
      owned: null
  - name: rules-names
    kind: generator
    layer: model
    tier: native
    package: @metaobjectsdev/codegen-ts
    description: "Per-package rules name constants: lifecycle states and transitions, derived commands, operations, permissions and business errors."
    useWhen: "hand-written code names a lifecycle state, a transition, a permission or a business error (a command body, a policy, a grant table) and you want a rename in the model to stop it compiling instead of leaving a stale string behind."
    emits: "<target>/<pkg path>/rules.names.ts per metadata package that declares a lifecycle or an operation, in either output layout. A model with no rules vocabulary gets no file."
    install:
      dev[1]: @metaobjectsdev/codegen-ts@^1.3.0
      runtime: []
    wire:
      import: "import { rulesNamesFile } from \"@metaobjectsdev/codegen-ts/generators\";"
    source:
      kind: reference-template
      ejectable: true
      owned: null
  - name: prisma-schema
    kind: generator
    layer: persistence
    tier: native
    package: @metaobjectsdev/codegen-ts
    description: "A Prisma schema (schema.prisma) for the model's tables, and schema.checks.sql for the CHECK constraints Prisma cannot declare, for a project that keeps Prisma as its ORM. Under orm: \"prisma\", entity writes the types and Zod schemas with no Drizzle table."
    useWhen: "the project keeps Prisma as its ORM and wants each field declared once, in the model. Pair it with `entity` under `orm: \"prisma\"`, which writes the types and Zod schemas with no Drizzle table."
    emits: "<target>/schema.prisma, one model per table `meta migrate` would create; and <target>/schema.checks.sql, the CHECK constraints a Prisma schema cannot declare (enum membership, numeric and length validators), when the model implies any. Apply it after `prisma db push` or a migration: `prisma db execute --file`."
    requires: []
    configKeys[2]: dialect,orm
    install:
      dev[1]: @metaobjectsdev/codegen-ts@^1.3.0
      runtime: []
    wire:
      import: "import { prismaSchemaFile } from \"@metaobjectsdev/codegen-ts/generators\";"
    source:
      kind: reference-template
      ejectable: true
      owned: null
  - name: queries
    kind: generator
    layer: persistence
    tier: native
    package: @metaobjectsdev/codegen-ts
    description: Per-entity typed query helpers (findById/create/...).
    useWhen: "you want generated typed CRUD finders (find<E>ById, list<E>s, create/update/delete) over Drizzle. Drop it if you hand-write your data access."
    emits: "<target>/<Entity>.queries.ts per source-backed object (any source.rdb kind, incl. read-only projections) — skipped for sourceless objects (incl. every object.value, source-less by value purity) and TPH subtypes (#248 R2)."
    requires[1]: entity
    configKeys[4]: dialect,extStyle,pluralizeCollections,collectionNameOverrides
    install:
      dev[1]: @metaobjectsdev/codegen-ts@^1.3.0
      runtime[2]: drizzle-orm,zod
    wire:
      import: "import { queriesFile } from \"@metaobjectsdev/codegen-ts/generators\";"
    source:
      kind: reference-template
      ejectable: true
      owned: null
  - name: service
    kind: generator
    layer: service
    tier: native
    package: @metaobjectsdev/codegen-ts
    description: "The service layer (ADR-0067): one module per package, a function per derived list, get, create, update and delete, each write in one transaction with the declared write rules."
    useWhen: "a route, a job, a queue consumer or an agent tool runs the model's writes, and every write has to take the same transaction and the same write rules."
    emits: "<pkg path>/service/<operation>.ts (one function per derived list, get, create, update and delete of every covered entity) and <pkg path>/service/index.ts (the `<Pkg>Service` interface, `create<Pkg>Service(deps)` and each entity's wire mapper), in either layout. A package with no covered entity gets no file."
    requires[2]: entity,contract-types
    configKeys[5]: dialect,extStyle,outputLayout,pluralizeCollections,collect
  • Outcome: 🔧 2 issues found → auto-fixed ✅ across 2 runs (41m34s)

Gate and scope

  • One no-mistakes gate run (01M815CBVCJFPXJ3GN6MNPWR5R). The "2 runs" above counts its fix rounds. The fixes were:
    • review-1, by owner decision: the service's sqlite Db type is now async-only, so a sync driver such as better-sqlite3 or bun:sqlite fails at type-check. The docs say the sqlite service needs an async driver such as libsql. A test pins the type.
    • review-3: the agent-context goldens and the shipped bundle were regenerated after the codegen skill changed.
    • test-1: the C# drift test listed the shared temp dir. A directory another process created there made it flaky, so it now counts only this port's GUID-named entries.
  • This is part 1 of the service layer. Not covered yet: write-through entities, TPH hierarchies, many-to-many, projections and reports (all stay on the flat generators), transitions, declared operations, the policy, bodies and events interfaces, the actor, Hono, sync sqlite drivers and D1 (ERR_STORE_NO_INTERACTIVE_TX), the init flag, and the verify advisory.

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 2 infos
  • ⚠️ server/typescript/packages/runtime-ts/src/service/index.ts:96 - The generated service runs every write through scope.transaction(fn) with an async callback, and service is registered for dialect: sqlite. dbTypeBlock(&#39;sqlite&#39;) types Db as BaseSQLiteDatabase&lt;&#34;sync&#34; | &#34;async&#34;, ...&gt;, so a sync Drizzle driver type-checks. Per my knowledge of Drizzle (no node_modules here, so I could not confirm in this worktree), a better-sqlite3 database throws "Transaction function cannot return a promise" on an async callback. A bun:sqlite database commits before the awaited statements run. In the first case every create, update and delete fails as a redacted 500. In the second a write can lose its atomicity and row lock silently. The runtime test uses libsql only, and its header comment notes that a sync driver differs. The compile gate builds sqlite output but does not run it. Neither docs/features/business-rules.md nor the generator docs say the sqlite service needs an async driver (libsql/D1). The remedy needs an owner decision: narrow the sqlite Db alias to &#34;async&#34; for the service, document the restriction, or add sync-driver handling in inWriteTransaction.
  • ℹ️ server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts:15 - Applied inline: the runtimeImport option doc on serviceRoutesFile said the emitted file imports from @metaobjectsdev/runtime-ts/drizzle-fastify. The emitted transport imports @metaobjectsdev/runtime-ts/service/fastify, so I corrected the comment. src/reference/service-routes.ts already says service/fastify.

🔧 Fix applied.
3 issues (1 error, 2 infos) still open:

  • ℹ️ server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts:15 - Applied inline: the runtimeImport option doc on serviceRoutesFile said the emitted file imports from @metaobjectsdev/runtime-ts/drizzle-fastify. The emitted transport imports @metaobjectsdev/runtime-ts/service/fastify, so I corrected the comment. src/reference/service-routes.ts already says service/fastify.
  • ℹ️ server/typescript/packages/codegen-ts/test/service-file.test.ts:67 - The fix round (5d9f1bd) narrowed the sqlite service Db to BaseSQLiteDatabase&lt;&#34;async&#34;, ...&gt; but added no test. The compile gate (service-compile.test.ts) only proves async output compiles. It cannot catch a regression to &#34;sync&#34; | &#34;async&#34;, which would silently bring back the runtime failure review-1 prevented. Add a generation test that emits the service for dialect: sqlite and asserts the emitted service/index.ts declares the async-only alias. The flat queries generator must keep &#34;sync&#34; | &#34;async&#34; (test/templates/queries-file.test.ts:84). The emitted file is generated public output, so asserting on it is a legitimate contract.
  • 🚨 agent-context/skills/metaobjects-codegen/SKILL.md:347 - The change edits the skill source (heading now 'The seven layers', new service row), but the committed outputs generated from it were not regenerated. agent-context-conformance.test.ts (sdk) assembles the stack from agent-context/ and asserts byte equality with each golden, so it fails. agent-context/shipped.test.ts ('the shared conformance goldens come out of the tree unchanged') compares the same goldens against the committed shipped tree, so it is stale too. The base-commit skill matched the goldens exactly, so the drift comes from this change. Stale goldens, each still reading 'The six layers, and what picks them' with no service row: fixtures/agent-context-conformance/{rust,python,java-react,java-kotlin-react-tanstack,csharp,ts-react-tanstack}/expected/.claude/skills/metaobjects-codegen/SKILL.md. Stale shipped bundle: agent-context-shipped/files/86974256b798cf22.md (the codegen SKILL, still 'six layers') plus agent-context-shipped/manifest.json, whose file hash and name for that entry also change. Fix: run bun scripts/regen-agent-context-conformance.ts in server/typescript/packages/sdk, then rebuild the shipped tree with whatever script owns agent-context-shipped/ (check its README), and commit both.

🔧 Fix applied.
📝 2 wording or comment-placement notes left for the author (no fix round spent):

  • ℹ️ server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts:15 - Applied inline: the runtimeImport option doc on serviceRoutesFile said the emitted file imports from @metaobjectsdev/runtime-ts/drizzle-fastify. The emitted transport imports @metaobjectsdev/runtime-ts/service/fastify, so I corrected the comment. src/reference/service-routes.ts already says service/fastify.
  • ℹ️ fixtures/generator-registry-conformance/registry.json:2 - Applied inline: the manifest's $comment still said layer is one of model, persistence, api, client, docs, capability. It omitted the new service layer that this change adds. I added service to that list. This is wording only, and the file still parses as JSON.
🔧 **Test** - 2 issues found → auto-fixed ✅
  • 🚨 configured test command failed with exit code 1
  • ℹ️ Docker-backed api-contract service lane and integration-tests were not run in this step (outside the affected selection). The intent names passing the shared API tests, so run scripts/ci-local.sh --only ts-slow before merge.
  • Live validation: ✅ go - 5 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Generated service + Fastify transport CRUD over HTTP (local libsql file DB, synthetic Note entity): POST 201, GET by id 200, list 200, PATCH 200 with DB row updated, DELETE 204, GET after delete 404 ✅ pass live service-live/drive.log (S1 lines); generated by meta gen from the fixture
Write rules on PATCH/POST: writeOnce field not overwritten on PATCH (200, stored value kept), unknown key on POST refused with 400 unknown_fields and nothing persisted, PATCH on missing row 404 with n… ✅ pass live service-live/drive.log (S2 lines)
Refusal rolls back with no partial write: PATCH with an over-long title (maxLength 80) returns 400 validation and row 2 is unchanged in the DB ✅ pass live service-live/drive.log (S3 lines)
sqlite service Db is async-only: a sync Drizzle driver (bun:sqlite) fails to typecheck against the generated service ✅ pass live service-live/sync-driver.ts and tsc run; error Type &#39;&#34;sync&#34;&#39; is not assignable to type &#39;&#34;async&#34;&#39;
Affected CI lanes for the change (ts build/typecheck/conformance/unit/completeness, java reactor, python, csharp, rust) pass at HEAD b0d350e ✅ pass live ci-affected-before.log: LOCAL CI PASSED, 5m19s
Docker api-contract service lane and integration-tests (shared API tests against the service behind its transport) ⏸️ untested no Not in the affected selection and needs Docker/Testcontainers Postgres. Its behavior is covered in CI by the api-contract service lane and service-compile gate; run `scripts/ci-local.sh --only ts-slow…
  • scripts/ci-local.sh --affected --strict-toolchains
  • scripts/ci-local.sh --affected --strict-toolchains on HEAD b0d350e0 (ts build+typecheck, ts conformance, ts unit suites, completeness-gate, java-reactor, python, csharp, rust lanes): LOCAL CI PASSED, total wall 5m19s
  • bun server/typescript/packages/sdk/scripts/build-shipped-agent-context.ts --check: agent-context-shipped current (101 files)
  • Live scenario fixture: meta gen via bun server/typescript/packages/cli/dist/bin/meta.js gen on a one-entity model (acme::shop Note: title maxLength 80, code writeOnce) with entityFile, queriesFile, contractTypes, serviceFile, serviceRoutesFile, barrel; emitted 12 files
  • Live driver bun drive.ts: generated createShopService bound to drizzle libsql over a file DB, served by generated shopServiceRoutes on Fastify at 127.0.0.1:4317; real HTTP requests; DB state read back with an independent libsql query
  • Typecheck: tsc -p tsconfig.json (strict, nodenext) over generated gen/**/*.ts: exit 0
  • Sync-driver probe: tsc -p tsconfig.sync.json with drizzle bun-sqlite passed to createShopService: error TS(Db) Type &#39;&#34;sync&#34;&#39; is not assignable to type &#39;&#34;async&#34;&#39;
  • Focused tests: codegen-ts test/service-file.test.ts (9 pass), runtime-ts test/service.test.ts (14 pass), sdk test/agent-context (138 pass), codegen-ts test/templates/queries-file.test.ts (6 pass)
  • Regression suites: bun test in codegen-ts (3889 pass, 0 fail), cli (2195 ran, 0 fail, 12 skip), sdk (542 pass, 0 fail), runtime-ts (1149 ran, 0 fail, 15 skip)
  • Fixture and driver torn down (scratch dir removed, port 4317 closed); no background processes left; worktree clean

🔧 Fix applied.
✅ Re-checked - no issues remain.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
Generated service module plus thin Fastify transport passes the shared api-contract corpus (HTTP lane against Testcontainers Postgres) ✅ pass live bun test test/api-contract-service.test.ts test/service-compile.test.ts in integration-tests: 80 pass, 0 fail. The lane generates the service and transport, boots them over HTTP, and the emitted cod…
The service runtime module runs derived writes in one transaction with write rules, and the generator registry lists the new layer (meta gen --list shows service, layer service, requires entit… ✅ pass live runtime-ts service.test.ts 14 pass. codegen-ts service-file.test.ts and generator-registry.test.ts 24 pass, including the async-only sqlite Db alias. The meta gen --list transcript is in gen…
Cross-port generator registry conformance accepts the new service layer, and the C# drift test ignores temp dirs from other tools ✅ pass live dotnet test in server/csharp: 11 pass in MetaObjects.Codegen.Tests, covering CodegenDriftTests and GeneratorRegistryConformance.
  • scripts/ci-local.sh --affected --strict-toolchains
  • Broad regression came from the configured scripts/ci-local.sh --affected --strict-toolchains, which passed at this commit and was not re-run.
  • bun test test/service.test.ts in runtime-ts: 14 pass.
  • bun test test/service-file.test.ts test/generator-registry.test.ts in codegen-ts: 24 pass.
  • bun test test/api-contract-service.test.ts test/service-compile.test.ts in integration-tests, which boots Testcontainers Postgres: 80 pass.
  • bun bin/meta.ts gen --list in the cli package: the output includes a service entry with layer: service.
  • dotnet test --filter &#34;CodegenDriftTests|GeneratorRegistryConformance&#34; in server/csharp: 11 pass in MetaObjects.Codegen.Tests.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

… (ADR-0067 part 1)

`service` writes one module per metadata package: a function per derived
list, get, create, update and delete of each concrete, table-backed,
single-key entity. Each write runs in one transaction (a savepoint inside
a caller's), loads the row under a row lock, and validates and stamps the
body with the declared write rules (ADR-0045). `service-routes` writes the
thin Fastify transport over it. Both are ejectable reference generators
written through TsWriter.

runtime-ts gains the `./service` and `./service/fastify` entries they
import, and `meta eject` copies them. The shared generator list gains the
`service` layer label in every port. A new api-contract lane runs the
shared corpus against the service behind its transport, in both layouts,
and a compile gate builds the tier in every dialect.
@dmealing
dmealing merged commit 261255f into main Nov 22, 2026
10 checks passed
@dmealing
dmealing deleted the fm/mo-130-lane-ts-2-b6 branch November 22, 2026 09:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant